//
//  TextfieldViewController.m
//  百度地图
//
//  Created by ljm on 2017/7/7.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "TextfieldViewController.h"
#import <MapKit/MKMapItem.h>

@interface TextfieldViewController ()
<UITextFieldDelegate>

{
    UITextField *_f1;
    UITextField *_f2;
    
    NSString *_f1String;
    NSString *_f2String;
    
    NSString *_startLatitude;
    NSString *_startLongitude;
    NSString *_destinationLatitude;
    NSString *_destinationLongitude;
    
    BOOL _isInstallBaidumap;
    BOOL _isInstalliosamap;
    BOOL _isInstallcomgooglemaps;
    BOOL _isInstallqqmap;
}

//@property (nonatomic, assign) CLLocationCoordinate2D place1;
//@property (nonatomic, assign) CLLocationCoordinate2D place2;

@end



@implementation TextfieldViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    Navigationbar_color = RGB(94, 194, 248);
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    Navigationbar_color = [UIColor clearColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"导航";
    
    [self setupUI];
    [self setupUserInterface];
    
    _isInstallBaidumap      =   [UIAPP_SHARED canOpenURL:[NSURL URLWithString:BMKMapParameter]];
    
    _isInstalliosamap       =   [UIAPP_SHARED canOpenURL:[NSURL URLWithString:AMAPParameter]];
    
    _isInstallcomgooglemaps =   [UIAPP_SHARED canOpenURL:[NSURL URLWithString:GOOGLEMapParameter]];
    
    _isInstallqqmap         =   [UIAPP_SHARED canOpenURL:[NSURL URLWithString:QQMapParameter]];
    
    NSLog(@"百度地图:%d"    ,   _isInstallBaidumap);
    NSLog(@"高德地图:%d"    ,   _isInstalliosamap);
    NSLog(@"谷歌地图:%d"    ,   _isInstallcomgooglemaps);
    NSLog(@"腾讯地图:%d"    ,   _isInstallqqmap);
    
    
}

#pragma mark -- setupUI
- (void) setupUI
{
    _f1         =   [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];
    _f2         =   [[UITextField alloc] initWithFrame:CGRectMake(0, 0, _f1.frame.size.width, _f1.frame.size.height)];
    
    _f1.center  =   CGPointMake(screenWidth / 2, screenHeight * 0.2);
    _f2.center  =   CGPointMake(_f1.center.x, _f1.frame.origin.y + _f1.frame.size.height * 2);
    
    
    /** 设置水印文字居中 **/
    NSMutableParagraphStyle *style  =   [[NSMutableParagraphStyle alloc] init];
    style.alignment                 =   NSTextAlignmentCenter;
    
    NSAttributedString *attr_f1     =   [[NSAttributedString alloc] initWithString:@"请输入起始点" attributes:@{NSParagraphStyleAttributeName:style}];
    NSAttributedString *attr_f2     =   [[NSAttributedString alloc] initWithString:@"请输入目的地" attributes:@{NSParagraphStyleAttributeName:style}];
    
    _f1.attributedPlaceholder       =   attr_f1;
    _f2.attributedPlaceholder       =   attr_f2;
    

    _f1.textAlignment               =   NSTextAlignmentCenter;
    
    _f2.textAlignment               =   NSTextAlignmentCenter;

    
    _f1.layer.borderWidth           =   1.f;
    _f1.layer.cornerRadius          =   5;
    _f1.layer.borderColor           =   [UIColor blackColor].CGColor;
    
    _f2.layer.borderWidth           =   _f1.layer.borderWidth;
    _f2.layer.cornerRadius          =   _f1.layer.cornerRadius;
    _f2.layer.borderColor           =   _f1.layer.borderColor;
    
    [_f1 addTarget       :  self action:@selector(f1_Clicked) forControlEvents:UIControlEventTouchDown];
    [_f2 addTarget       :  self action:@selector(f2_Clicked) forControlEvents:UIControlEventTouchDown];
    
    [self.view addSubview:  _f1];
    [self.view addSubview:  _f2];
    
    
    /**
     *    开始导航
     */
    UIButton *startBtn  =   [[UIButton alloc] initWithFrame:CGRectMake(0,
                                                                       0,
                                                                       _f1.frame.size.width ,
                                                                       _f1.frame.size.height * 0.8)];
    startBtn.center     =   CGPointMake(screenWidth * 0.5, screenHeight - _f1.frame.size.height);
    startBtn.backgroundColor        =   RGB(102, 244, 102);
    [startBtn setTitle:@"开始导航" forState:UIControlStateNormal];
    [startBtn setTitleColor         :   [UIColor whiteColor] forState:UIControlStateNormal];
    startBtn.layer.cornerRadius     =   20;
    startBtn.layer.masksToBounds    =   YES;
    
    [startBtn addTarget             :   self action:@selector(startNavigation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview           :   startBtn];
    
}

#pragma mark -- 开始导航
- (void) startNavigation{
    
    
    //转成UTF8  [NSCharacterSet URLQueryAllowedCharacterSet]
    //四个参数分别是, 当前位置纬度, 经度, 目的地纬度, 经度
//    NSString *url = [[NSString stringWithFormat:@"baidumap://map/direction?origin=%f,%f&destination=%f,%f&mode=driving&src=webapp.navi.yourCompanyName.yourAppName", _currentLatitude, _currentLongitude, _latitude, _longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    
//    //根据起点终点跳转到百度地图并进行驾车导航
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    
    
    if (_startLatitude == NULL || _startLongitude == NULL || _destinationLatitude == NULL || _destinationLongitude == NULL) {
        
        NSLog(@"%@",_startLongitude);
        [SVProgressHUD showErrorWithStatus:@"请输入正确的地址"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            return ;
        });
    }else
    {
    
    //百度地图
   if (_isInstallBaidumap)
   {
       NSLog(@"正在打开百度地图……");
       [SVProgressHUD showSuccessWithStatus:@"正在为您打开百度地图"];
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
           //四个参数分别是, 当前位置纬度、 经度，地址, 目的地纬度, 经度，地址
           NSString *urlString = [[NSString stringWithFormat:
                                   
                                   @"baidumap://map/direction?origin=latlng:%@,%@|name:%@&destination=latlng:%@,%@|name:%@&mode=driving",
                                   
                                   _startLatitude,
                                   _startLongitude,
                                   _f1String,
                                   _destinationLatitude,
                                   _destinationLongitude,
                                   _f2String]
                                  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ;
           
           [UIAPP_SHARED openURL:[NSURL URLWithString:urlString]];
           
           [SVProgressHUD dismiss];
           
       });
       
   }else if (_isInstalliosamap)
   {
       NSLog(@"正在打开高德地图……");
       
       [SVProgressHUD showSuccessWithStatus:@"正在为您打开高德地图"];
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
           
           NSString *urlString = [[NSString stringWithFormat:
                                   @"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%@&lon=%@&dev=0&style=2",@"导航功能",@"nav123456",
                                   _destinationLatitude,
                                   _destinationLongitude]
                                  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
           
           [UIAPP_SHARED openURL:[NSURL URLWithString:urlString]];
           
           [SVProgressHUD dismiss];
       });
       
       
   }
   
   else if (_isInstallcomgooglemaps)
   {
       NSLog(@"正在打开谷歌地图……");
       
       [SVProgressHUD showSuccessWithStatus:@"正在为您打开谷歌地图"];
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
           NSString *urlString = [[NSString stringWithFormat:
                                   @"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%@,%@&directionsmode=driving",@"导航测试",@"nav123456",
                                   _destinationLatitude,
                                   _destinationLongitude]
                                  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
           
           [UIAPP_SHARED openURL:[NSURL URLWithString:urlString]];
           [SVProgressHUD dismiss];
           
       });
       
       
   }else if (_isInstallqqmap)
   {
       NSLog(@"正在打开腾讯地图……");
       
       [SVProgressHUD showSuccessWithStatus:@"正在为您打开腾讯地图"];
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
           NSString *urlString = [[NSString stringWithFormat:
                                   @"qqmap://map/routeplan?from=%@&type=drive&tocoord=%@,%@&to=%@&coord_type=1&policy=0",
                                   _f1String,
                                   _destinationLatitude,
                                   _destinationLongitude,
                                   _f2String]
                                  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
           
           [UIAPP_SHARED openURL:[NSURL URLWithString:urlString]];
           [SVProgressHUD dismiss];
           
       });
       
   }else
   {
       
       
       UIAlertController *alertvc = [UIAlertController alertControllerWithTitle:@"提示" message:@"你的手机没有安装任何地图" preferredStyle:UIAlertControllerStyleAlert];
       UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           NSLog(@"nothing");
       }];
       [alertvc addAction:action];
       [self.navigationController presentViewController:alertvc animated:YES completion:nil];
   }
    
    }
    
    
//    BMKOpenTransitRouteOption* opt = [[BMKOpenTransitRouteOption alloc] init];
//    
//    opt.appScheme = @"abyss_vmApp://";
//    
//    BMKPlanNode* start = [[BMKPlanNode alloc] init];
//    
//    start.name = _f1String;
//    NSLog(@"<><><><><><><><><><><><><\n%@\n<><><><><><><><><><><",_f1String);
//    if (_place1.longitude > 0) {
//        start.pt = _place1;
//    }
//    
//    opt.startPoint = start;
//    
//    BMKPlanNode* end = [[BMKPlanNode alloc] init];
//    
//    end.name = _f2String;
//    NSLog(@"><><><><><><><><><><<><<\n%@\n>>><><><><><><><><>><<>",_f2String);
//    if (_place2.longitude > 0) {
//        end.pt = _place2;
//    }
//    
//    opt.endPoint = end;
//    
//    BMKOpenErrorCode code = [BMKOpenRoute openBaiduMapDrivingRoute:opt];
}


#pragma mark -- 设置功能，点击空白处收起键盘
- (void) setupUserInterface
{
    _f1.userInteractionEnabled = YES;
    _f2.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    [self.view addGestureRecognizer:singleTap];
}


#pragma mark -- actions
- (void) f1_Clicked
{
    BMKMapViewController *mapVC =   [[BMKMapViewController alloc] init];
    mapVC.addressBlock          =   ^(NSDictionary *dataDic) {
        _f1String               =   [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"address"]];
        _startLatitude          =   [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"lat"]];
        _startLongitude         =   [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"lon"]];
        _f1.text                =   _f1String;
    };
    
    [self.navigationController pushViewController:mapVC animated:YES];
    
}

- (void) f2_Clicked
{
    BMKMapViewController *mapVC =   [[BMKMapViewController alloc] init];
    mapVC.addressBlock          =   ^(NSDictionary *dataDic) {
        _f2String               =   [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"address"]];
        _destinationLatitude    =   [NSString stringWithFormat:@"%@", [dataDic objectForKey:@"lat"]];
        _destinationLongitude   =   [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"lon"]];
        _f2.text = _f2String;
    };
    [self.navigationController pushViewController:mapVC animated:YES];

}

#pragma mark -- 点击空白处收起键盘
-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer
{
    [self.view endEditing:YES];
    
}


@end
